<?php

namespace App\Common\ElasticSearch;

use App\Common\Utill\ElasticSearch;
use Illuminate\Support\Facades\Log;

/**
 * Class CreateIndex
 * 任务时间记录表
 *
 * @package App\Common\ElasticSearch
 *
 */
class DrawLuckLog
{

    /**
     * 创建索引
     * @return array
     * @throws \Exception
     *
     */
    public static function create_index(string $indexName="",$isSql=false)
    {
        //mappings
        $mappings = [
            "id"           => ["type" => "long"],     //用户id
            "luck_id"      => ["type" => "long"],     //签到的类型
            "user_id"      => ["type" => "long"],     //次数
            "draw_id"      => ["type" => "long"],     //经验值
            "luck_name"    => ["type" => "text"],     //描述
            "draw_name"    => ["type" => "text"],     //描述
            "user_name"    => ["type" => "text"],     //描述
            "draw_time"    => [
                "type"   => "date",
                "format" => "yyyy-MM-dd HH:mm:ss",
                "fields" => [
                    "keyword" => [
                        "type"         => "keyword",
                        "ignore_above" => 256
                    ]
                ]
            ],//创建时间
        ];
        $settings = [
        ];
        if (!$indexName){
            $indexName = "draw_luck_log_".date("Y-m");
        }
        $res      = (new ElasticSearch())->settings([], 3, 1)->mappings($mappings)->createIndex($indexName);
        if (!empty($res['acknowledged']) && !empty($res['index'])){
            $resData['code'] = 200;
            $resData['msg'] = $res['index']."创建成功";
            return $resData;
        }
        $resData['code'] = $res['status']??500;
        $resData['msg'] = $indexName."创建失败。原因：".$res['error']['reason']??"";
        Log::info('ES索引{'.$indexName.'}创建失败:'.$resData['msg']);
        return $resData;
    }

    /**
     * 写入
     * @param array  $params
     * @param bool   $isSql
     * @param string $index
     *
     * @return array|bool
     * @throws \Exception
     */
    public static function insert(array $params,string $index="",bool $isSql=false)
    {
        if (empty($params['user_id']) || empty($params['sign_type'])) {
            return [
                "code"=>500,
                "msg"=>"user_id,sign_type为必填参数"
            ];
        }
        $insertInfo = [
            "user_id"        => $params["user_id"],
            "sign_type"      => $params['sign_type'],
            "sign_num"       => $params['sign_num'] ?? 1,
            "exp_value"      => $params['exp_value'] ?? 0,
            "notes"          => $params['notes'] ?? "",
            "anchor_user_id" => $params['anchor_user_id'] ?? 0,
            "live_no"        => $params['live_no'] ?? "",
            "live_log_id"    => $params['live_log_id'] ?? 0,
            "date_time"      => date("Y-m-d"),
            "created_at"     => date("Y-m-d H:i:s"),
        ];
        // 判断可选参数index是否为指定索引，不是则默认当前月份
        if (empty($index) || !strpos($index, "task_time_record_")){
            $index      = "task_time_record_" . date("Y-m");
        }
        if (!ElasticSearch::instance()->index($index)->checkIndexExists()) {
            Log::info("自动创建索引".$index);
            self::create_index();
        }
        return ElasticSearch::instance()->index($index)->data($insertInfo)->isSql($isSql)->saveOneById($params["user_id"]);
    }

    /**
     * 获取列表
     *
     * @param array $params
     *              参数说明：[
     *                     date_time:日期,
     *                     user_id:单用户
     *                     user_id_list:多用户ID
     *                     sign_type:单签到类型
     *                     sign_type_list:多签到类型
     *                     page:当前页数
     *                     size:每页数量
     *              ]
     * @param bool  $isSql
     *
     * @return array
     * @throws \Exception
     */
    public static function getList(array $params,bool $isSql=false)
    {
        $mustTerm = [];
        $mustTerms = [];
        $index = "task_time_record_*";
        // 日期
        if (!empty($params['date_time']) && is_string($params['date_time'])){
            $mustTerm[] = ["date_time"=>$params];
            if (strtotime($params['date_time']) > 0){
                $index = "task_time_record_".date("Y-m",strtotime($params['date_time']));
            }
        }
        //单用户ID
        if (!empty($params['user_id']) && is_numeric($params['user_id'])){
            $mustTerm[] = ["user_id"=>$params['user_id']];
        }
        // 多用户ID查询
        if (!empty($params['user_id_list']) && is_array($params['user_id_list'])){
            $mustTerms['user_id'] = $params['user_id_list'];
        }
        // 单签到类型
        if (!empty($params['sign_type']) && is_numeric($params['sign_type'])){
            $mustTerm[] = ["sign_type"=>$params['sign_type']];
        }
        // 多签到类型
        if (!empty($params['sign_type_list']) && is_array($params['sign_type_list'])){
            $mustTerms['user_ids'] = $params['user_id_list'];
        }
        if ($mustTerm) {
            $where = [
                "must"=>[
                    'term' => $mustTerm
                ]
            ];
        }
        if ($mustTerms){
            $where['must']['terms'] = $mustTerms;
        }
        dump($where);
        $db = ElasticSearch::instance()->index($index)->where($where);
        if (isset($params['page']) && isset($params['size'])){
            $db = $db->pageSize($params['page'],$params['size']);
        }

        return $db->isSql($isSql)->search();
    }
}
